package com.dianrui.agent.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.dianrui.agent.R;
import com.dianrui.agent.activity.BigImagesActivity;
import com.dianrui.agent.activity.DeviceInfoActivity;
import com.dianrui.agent.activity.LoginActivity;
import com.dianrui.agent.activity.ShowLocationActivity;
import com.dianrui.agent.adapter.DeviceListAdapter;
import com.dianrui.agent.bean.DeviceList;
import com.dianrui.agent.event.DeviceNormalRfresh;
import com.dianrui.agent.event.DeviceRedDot;
import com.dianrui.agent.okhttp.OkHttpRequest;
import com.dianrui.agent.util.SharedUtil;
import com.dianrui.agent.util.StringUtils;
import com.dianrui.agent.util.ToastUtil;
import com.dianrui.agent.util.Url;
import com.dianrui.agent.view.pulltoRefresh.PullToRefreshBase;
import com.dianrui.agent.view.pulltoRefresh.PullToRefreshListView;
import com.google.gson.JsonObject;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 运营中
 */
public class DeviceOperationFragment extends BaseFragment {
    private DeviceListAdapter deviceListAdapter;
    private int pageIndex = 1;
    private List<DeviceList> vehicleListAll = new ArrayList<>();
    private List<Integer> totalNums = new ArrayList<>();
    private List<String> qrList = new ArrayList<>();


    @BindView(R.id.device_list)
     ListView deviceList;
    @BindView(R.id.emptyView)
    LinearLayout emptyView;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;



    @Override
    public int getContentViewId() {
        return R.layout.fragment_device_list;
    }

    @Override
    public void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        deviceListAdapter = new DeviceListAdapter(getActivity(), vehicleListAll);
        deviceList.setAdapter(deviceListAdapter);
        getDeviceList(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getDeviceList(true);
                refreshLayout.finishRefresh();
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageIndex++;
                getDeviceList(false);
            }
        });
        deviceListAdapter.setOndeviceClickListener(new DeviceListAdapter.DeviceClickListener() {


            @Override
            public void showLocation(String usestatus, String glat, String glng, String number, String vehicle_status, int battery) {
                Intent intent = new Intent(getActivity(), ShowLocationActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("lat", glat);
                bundle.putString("lng", glng);
                bundle.putString("number", number);
                bundle.putString("usestatus", usestatus);
                bundle.putString("vehicle_status", vehicle_status);
                bundle.putInt("battery", battery);
                intent.putExtras(bundle);
                startActivity(intent);
            }


            @Override
            public void ClickInfo(String vehicleId) {
                getActivity().startActivity(new Intent(getActivity(), DeviceInfoActivity.class)
                        .putExtra("vehicleId", vehicleId));
            }

            @Override
            public void showCode(String qrUrl) {
                startActivity(new Intent(getActivity(), BigImagesActivity.class)
                        .putExtra("qrImages", qrUrl));
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(DeviceNormalRfresh deviceListRfresh) {
        getDeviceList(true);
    }

    public void getDeviceList(final boolean isRfresh) {
        if (isRfresh) {
            pageIndex = 1;
        }
        JsonObject deviceListJson = new JsonObject();
        deviceListJson.addProperty("status", "1");
        deviceListJson.addProperty("type_id", "2");
        deviceListJson.addProperty("p", pageIndex);
        OkHttpRequest.getInstance().postTokenRequests(SharedUtil.getUrl() + Url.DEVICE_LIST, deviceListJson.toString(), new OkHttpRequest.XCallBack() {

            @Override
            public void onResponse(String result) {

                if (isRfresh) {
                    vehicleListAll.clear();
                }
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject != null && isAdded()) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                if (totalNums != null) {
                                    totalNums.clear();
                                }
                                if (qrList != null) {
                                    qrList.clear();
                                }
                                JSONArray totalNum = jsonObject.optJSONObject("data").optJSONArray("total_num");
                                for (int i = 0; i < totalNum.length(); i++) {
                                    int str = totalNum.optInt(i);
                                    totalNums.add(str);
                                }
                                List<Integer> countNum = totalNums;
                                EventBus.getDefault().post(new DeviceRedDot(countNum));

                                JSONArray vehicleLists = jsonObject.optJSONObject("data").optJSONArray("vehicle_list");
                                if (vehicleLists.length() > 0) {
                                    for (int i = 0; i < vehicleLists.length(); i++) {
                                        DeviceList deviceList = new DeviceList();
                                        deviceList.vehicle_id = vehicleLists.optJSONObject(i).optString("vehicle_id");
                                        deviceList.device = vehicleLists.optJSONObject(i).optString("device");
                                        deviceList.vehicle_status = vehicleLists.optJSONObject(i).optString("vehicle_status");
                                        deviceList.number = vehicleLists.optJSONObject(i).optString("number");
                                        deviceList.online_status = vehicleLists.optJSONObject(i).optString("online_status");
                                        deviceList.glat = vehicleLists.optJSONObject(i).optString("glat");
                                        deviceList.create_time = vehicleLists.optJSONObject(i).optString("create_time");
                                        deviceList.qr_code = vehicleLists.optJSONObject(i).optString("qr_code");
                                        deviceList.remark = vehicleLists.optJSONObject(i).optString("remark");
                                        deviceList.mileage = vehicleLists.optJSONObject(i).optString("mileage");
                                        deviceList.order_number = vehicleLists.optJSONObject(i).optString("order_number");
                                        deviceList.glng = vehicleLists.optJSONObject(i).optString("glng");
                                        deviceList.status = vehicleLists.optJSONObject(i).optString("status");
                                        deviceList.use_status = vehicleLists.optJSONObject(i).optString("use_status");
                                        deviceList.vehicle_status = vehicleLists.optJSONObject(i).optString("vehicle_status");
                                        deviceList.battery = vehicleLists.optJSONObject(i).optInt("battery");
                                        deviceList.condition = vehicleLists.optJSONObject(i).optString("condition");
                                        qrList.add(vehicleLists.optJSONObject(i).optString("qr_code"));
                                        vehicleListAll.add(deviceList);
                                    }
                                    if (deviceListAdapter != null) {
                                        deviceListAdapter.refresh(vehicleListAll);
                                    }
                                    refreshLayout.finishRefresh();
                                }
                            }else if ("1001".equals(jsonObject.optString("status"))) {
                                refreshLayout.finishRefresh();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }else if ("1002".equals(jsonObject.optString("status"))) {
                                refreshLayout.finishRefresh();
                                spUtils.clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                JumpActivitys(LoginActivity.class);
                                getActivity().finish();
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                if (vehicleListAll.size() <= 0) {
                    emptyView.setVisibility(View.VISIBLE);
                    deviceList.setVisibility(View.GONE);
                } else {
                    emptyView.setVisibility(View.GONE);
                    deviceList.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void FailedRequest(String result) {
                if (isAdded()) {
                    ToastUtil.showToast(getResources().getString(R.string.net_error));
                }

            }
        });
    }




    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
